package com.spboot.controller;

import java.util.Arrays;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LoginController {

	@RequestMapping("/")
	public String login(){
		return "index";
	}
	
	@RequestMapping("/doLogin")
	public String doLogin(String userCode,String userPassword,Model model){
		//1
		Subject subject = SecurityUtils.getSubject();
		//token
		UsernamePasswordToken token = new UsernamePasswordToken(userCode, userPassword);
		try {
			subject.login(token);
			return "redirect:main";
		}catch(UnknownAccountException e){
			//账号不存在
			model.addAttribute("error", "账号不存在!");
		}catch(IncorrectCredentialsException e){
			//密码错误
			model.addAttribute("error", "密码错误!");
		}
		catch (Exception e) {
			//其他
			model.addAttribute("error", "登录失败!");
		}
		return "/";
	}

	@RequestMapping("/main")
	public String main(){
		return "main";
	}

	@RequestMapping("/logout")
	public String logout(){
		SecurityUtils.getSubject().logout();
		return "/";
	}
}
